﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using FlickrSample.SL.Infrastructure;
using FlickrSample.SL.Infrastructure.Flickr.Entities;
using GalaSoft.MvvmLight.Command;
using XamlingCore.Infrastructure.View;

namespace FlickrSample.View.User
{
    public class UserSearchViewModel : XContentViewModelBase
    {
        public RelayCommand DoSearchCommand { get; set; }

        private string searchUserName;

        private bool noResult;

        private Action<FlickrUser> userAddedCallback;

        public override void OnInitialise()
        {
            init();
        }

        void init()
        {
            Title = "find user";
            DoSearchCommand = new RelayCommand(onDoSearch);
        }

        private void onDoSearch()
        {
            IsLoading = true;
            ServiceLocator.SearchRepo.FindUserByUserName(SearchUserName, (result) =>
            {
                NoResult = result == null;
                if (!NoResult)
                {
                    ServiceLocator.UserRepo.GetUserDetail(result, (updated) =>
                                                                      {
                                                                          if (!updated)
                                                                          {
                                                                              MessageBox.Show(
                                                                                  "Problem finding user details");
                                                                          }
                                                                          if (UserAddedCallback != null) UserAddedCallback(result);
                                                                          IsLoading = false;
                                                                      });

                }
                else
                {
                    IsLoading = false;
                }
                
            });
        }

        public bool NoResult
        {
            get { return noResult; }
            set
            {
                noResult = value;
                OnPropertyChanged("NoResult");
            }
        }

        public string SearchUserName
        {
            get { return searchUserName; }
            set
            {
                searchUserName = value;
                OnPropertyChanged("SearchUserName");
            }
        }

        public Action<FlickrUser> UserAddedCallback
        {
            get { return userAddedCallback; }
            set { userAddedCallback = value; }
        }
    }
}
